<?php
class JournalCash extends AppModel {
    var $belongsTo = array(
        'Transaction'
    );
    
    function getTotal($month = null, $year = null, $balanceinquiry = false) {
        if ( is_null($month) ) {
            $month = date('m');
        }
        
        if ( is_null($year) ) {
            $year = date('Y');
        }
        
        $ret = array(
            'balance' => null, 'total_debit' => null,
            'total_credit' => null, 'year' => $year,
            'month' => $month
        );
        
        $conditions = array(
            $this->alias . '.transaction_date <' => $year . '-' .
                    $month . '-01'
        );
        
        if ( $balanceinquiry ) {
            $conditions = array(
                $this->alias . '.transaction_date <=' => date('Y-m-d')
            );
        }
        
        $this->Behaviors->attach('Containable');
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'fields' => array('debit_amount', 'credit_amount', 'transaction_id', 'tax_code'),
            'contain' => array(
                'Transaction' => array('amount_out')
            )
        ));
        
        // holds all transaction_id that have been counted
        $transaction_stacks = array();
        foreach ($t as $k => $r) {
            $ret['total_debit']  += $r[$this->alias]['debit_amount'];
            /**
             * This is a quick hack for fixing amount on kas umum.
             * Seharusnya credit_amount di journal_cash itu jumlahnya
             * belum dikurangi tax. Kalau fix ini, sekalian yg di model transaction
             */
            if ( !isset($transaction_stacks[ $r['Transaction']['id'] ]) &&
                 $r[$this->alias]['credit_amount'] > 0 ) {
                $ret['total_credit'] += $r['Transaction']['amount_out'];
                $transaction_stacks[ $r['Transaction']['id'] ] = $r['Transaction']['amount_out'];
            }
        }
        $ret['balance'] = $ret['total_debit'] - $ret['total_credit'];
        
        return $ret;
    }
}
?>
